import { existsSync, outputFileSync, readFileSync } from "fs-extra";
import { resolve } from 'path';
import { Queque } from '../utils/quque';
import { log } from '../shared/log';

var pwd = process.cwd();
var path = require('path')
var requireContext = require('node-require-context')
var fs = require('fs-extra');
var my_path = 'D:/项目/多平台/dist/dev/mp-weixin'
export interface FileTool {
    allFileList?: any[]
}
export class FileTool implements FileTool {
    allFileList?: any[] = []
    UglifyJS?: any
    options = {
        // 解析配置
        parse: {},
        // 压缩配置
        compress: {
            drop_console: true,
        },
        // 混淆配置
        mangle: {},
        // 输出配置
        output: {
            comments: false,    // 移除注释
        },
        sourceMap: {},
        ecma: 8,  // specify one of: 5, 6, 7 or 8
        keep_fnames: false,   // 防止丢弃或损坏函数名
        keep_classnames: false,
        toplevel: false,    // 混淆最高作用域中的变量和函数名
        warnings: false,
    }
    pageDirPath: any;
    constructor({
        data,
        UglifyJS
    }) {

        this.pageDirPath = path.resolve(pwd, data.pages);
        this.UglifyJS = UglifyJS;
    }
    // 获取所有文件
    getAllFileList() {
        const context = requireContext(my_path, true, /\.js$/)
        let arr: any[] = []
        context.keys().forEach((moduleId: string, index: number) => {
            let data = readFileSync(moduleId);
            let str = String(data) as never;
            let temp = {
                path: moduleId,
                code: str,
                index
            }
            arr.push(temp)
        })
        this.allFileList = arr
        return this.allFileList;
    }
    start() {
        let flag = existsSync(this.pageDirPath)
        if (flag) {
            new Queque({
                quque: this.getAllFileList(),
                limitTime: 200,
                callBack: this.mini.bind(this)
            });
        } else {
            console.error('您输入的文件夹不存在')
        }

        // this.getAllFileList().forEach(ele => {
        //     this.mini(ele)
        // })
    }
    // 压缩文件
    mini(val: any) {
        log(`任务进行中第${val.index + 1}个${val.path},剩余${this.getAllFileList().length - val.index - 1}`)
        let result = this.UglifyJS.minify(val.code, this.options);
        outputFileSync(val.path, result.code)
    }
    // 压缩成功
    success() {

    }
    // 压缩失败
    error() {

    }
}

